package lyc.springcloud.admin.controller;

import lombok.extern.slf4j.Slf4j;
import lyc.springcloud.admin.dao.LoginDao;
import lyc.springcloud.admin.dto.LoginDto;
import lyc.springcloud.admin.dto.PCIKeyPair;
import lyc.springcloud.admin.service.def.LoginService;
import lyc.springcloud.admin.utils.CommonResClass;
import lyc.springcloud.admin.utils.SM2Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

@RestController
@Slf4j
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private LoginDao loginDao;

    /**
     * 生成SM2密钥对，直接保存到DB
     * */
    @GetMapping("createSM2KeyPair")
    public void createSM2KeyPair() throws NoSuchAlgorithmException {
        PCIKeyPair keyPair =  SM2Util.genKeyPair();
        log.info("生成SM2密钥对，直接保存到DB:{}", keyPair.toString());
        loginDao.createSM2KeyPair(keyPair);
    }

    /**
     * 登录
     * */
    @PostMapping("login")
    public CommonResClass login(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @RequestBody LoginDto params) throws Exception {
        try {
            Map<String, Object> map = loginService.login(httpServletRequest, httpServletResponse, params);
            return CommonResClass.success(map);
        }catch (Exception e) {
            log.error("登录报错:", e);
            return CommonResClass.failure(e.getMessage());
        }
    }
}
